<?php
declare (strict_types = 1);
namespace app\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\captcha\facade\Captcha;
use app\Common;

//登录类
class Login{
    public function index($target='admin'){

        if(Request::method() == 'POST'){
            // 检测输入的验证码是否正确，$value为用户输入的验证码字符串
            $all = Request::param(); 
            $back = "<script>setTimeout(function(){history.back();},3000)</script>";

            if(empty($all['verify'])) {
                return Common::error("请输入验证码!").$back;
            }

            if(!captcha_check($all['verify'])){
               return Common::error("验证码错误！").$back;
            }

            $user = Db::table('user')->whereRaw('uid=? or mobile=?',[$all['account'],$all['account']])->find();
            if(empty($user)){
                return Common::error("未找到用户！".$back);
            }

            $pwd=Common::scode()($all['pwd']."think");
            if($pwd != $user['password']){
               return Common::error("密码错误！".$back);
            }

            if(Common::scode()($pwd.$user['create_time'])!=$user['verify_code']){
               return Common::error('密码校验异常,用户信息可能被篡改,请联系平台！'.$back);
            }

            if($user['status']==2){
                return Common::error("账户已关闭!".$back);
            }

            $login_info=array(
                'login_ip' => $_SERVER['REMOTE_ADDR'],
                'login_time'=>date('Y-m-d H:i:s'),
                'id'=>$user['id']
            );
            Db::table('user')->update($login_info);

            if($user['password']==Common::scode()('12345think'))
                Session::set('pwd_msg',"注意:你的密码为初始密码(12345),请尽快修改！");
            else
                Session::delete('pwd_msg');

            Session::set('logonid',$user['id']);
            Session::set('uid',$user['uid']);

           header("location:/index.php/".$target);


        }else{
            $sys = Db::table("sys")->find(1);
            Session::set('sys',$sys);
            View::assign([
                'sys'=>$sys,
                'target'=>$target,

                ]);

            return View::fetch();
        }
    }


    public function verify(){
        return Captcha::create();
    }

    public function logout($target='index'){
        Session::delete('logonid');
        Session::delete('uid');
        Session::delete('uname');
        Session::delete('utype');
        header("location:/index.php/login");
    }


    //app登录
    public function customer_login(){
            
            $all = Request::param(); 
            //halt($all);

            // if(empty($all['verify'])) {
            //     return json(['code'=>0,'msg'=>"请输入验证码!"]);
            // }
            //检测输入的验证码是否正确，$value为用户输入的验证码字符串
            if(!captcha_check($all['verify'])){
               return json(['code'=>0,'msg'=>"验证码错误！"]);
            }
            
            if(empty($all['mobile']) || empty($all['password']))  {
                return json(['code'=>0,'msg'=>"请输入手机号码及密码登录！"]);
            }
            $mobile = $all['mobile'];
            $password = $all['password'];

            $pwd = Common::scode()(trim($all['password']).'think');
            $cust = Db::query("select * from customer where mobile=?",[$mobile]); 
            if(!count($cust)){
                return json(['code'=>0,'msg'=>"资料不存在！".$mobile]);
            }
            $cust= $cust[0];

            if($pwd != $cust['password']){
                return json(['code'=>0,'msg'=>"密码错误！"]);
            }

            if($cust['money_v']!=Common::scode()($cust['create_time'].$cust['money'])){
                return json(['code'=>0,'msg'=>"账户金额异常，登录失败！"]);
            }

            //登录通过
            $token = $this->make_token();
            $new_time_out = time() + 604800; //604800是七天

            $login_info=array(
                'id'=>$cust['id'],
                'login_ip' => $_SERVER['REMOTE_ADDR'],
                'login_time'=>date('Y-m-d H:i:s'),
                'token'=>$token,
                'time_out'=>$new_time_out,
                'name'=>$cust['name'],
            );

            $res = Db::table('customer')->update($login_info);
            Db::execute("update user set token=?,time_out=? where mobile=?",[$token,$new_time_out,$mobile]); //如果是加盟商，更新用户表的token

            Session::set('logonid',$cust['id']);
            Session::set('uname',$cust['name']);

            return json(['code'=>1,'msg'=>'登录成功','customer'=>$login_info]);

    }

    //token验证
    public function check_token($token){
        if(empty($token)) return ["code"=>0,'msg'=>'token 无效!'];
        $user = Db::table('user')->where('token',$token)->select()->toArray();

        if(!empty($user)){
            if(time()-$user['time_out']>1){
                return json(["code"=>0,'msg'=>'token长时间未使用而过期，需重新登陆!']);
            }
            $user=$user[0];
            $new_time_out = time() + 604800; //604800是七天
            $token = $this->make_token();

            $login_info=array(
                'id'=>$user['id'],
                'login_ip' => $_SERVER['REMOTE_ADDR'],
                'login_time'=>date('Y-m-d H:i:s'),
                'token'=>$token,
                'time_out'=>$new_time_out
            );

            $res = Db::table('user')->update($login_info);
            if($res){
                $user['token']=$token;
                return ["code"=>1,"user"=>$user,"msg"=>"登录成功"];
            }
        }

        return ['code'=>0,'msg'=>"token错误验证失败"];
    }


    public function make_token($str=''){
        return  sha1(md5(time()."x")); 
    }


}
